package com.yzy.controller;

import com.yzy.annotation.UserLoginToken;
import com.yzy.entity.File;
import com.yzy.entity.Goods;
import com.yzy.entity.Order;
import com.yzy.service.FileService;
import com.yzy.util.Message;
import com.yzy.util.ResponseCode;
import com.yzy.util.TokenUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.yzy.util.ResponseCode;
import com.yzy.util.TokenUtil;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;

@RestController
@RequestMapping("/file")
@PropertySource(value = "classpath:application.yml")
public class FileController {

    @Value("${spring.file-path}")
    String path;

    @Resource
    private FileService fileService;


    @GetMapping("/all")
    public Object all() {
        List<File> list = fileService.list();
        Map<String, List> map = new HashMap<>();
        map.put("data", list);

        return map;
    }

    @UserLoginToken
    @GetMapping("/search")
    public Object search() {
        String uploadUserId = TokenUtil.getTokenUserId();
        List<File> list = fileService.search(Integer.valueOf(uploadUserId));
        Map<String, List<File>> map = new HashMap<>();
        map.put("data", list);
        return ResponseCode.buildSuccess(map);
    }

    /**
     * @param files 前端上传封装成对象
     * @return java.lang.Object
     * @description 用户上传多个文件
     * @author mgl
     * @date 2023/7/16 11:00
     */
    @UserLoginToken
    @PostMapping("/uploadFiles")
    public Object uploadList(MultipartFile[] files) {

        //判断文件是否存在
        java.io.File file = new java.io.File(path);
        if (!file.exists()) {
            file.mkdir();
        }
        if (files.length == 0) return ResponseCode.buildFailed(Message.NO_FILE_SELECTED);
        List<File> list = new ArrayList<>();
        for (MultipartFile multipartFile : files) {
            //获取上传文件的名称
            String filename = multipartFile.getOriginalFilename();
            //修改文件名称
            if (filename == null) return ResponseCode.buildFailed(Message.UPLOAD_FAILURE);
            String suffix = filename.substring(filename.lastIndexOf("."));

            System.out.println("suffix: " + suffix);
            if (!suffix.equals(".doc") && !suffix.equals(".pdf") && !suffix.equals(".docx")) {
                return ResponseCode.buildFailed(Message.FILE_FORMAT_ERROR);
            }
            //拼接文件名
            String newName = path + java.io.File.separator + System.currentTimeMillis() + suffix;
            try {
                //上传
                multipartFile.transferTo(new java.io.File(newName));

                //封装javabean对象
                File entity = new File();
                entity.setUploadUserId(Integer.valueOf(TokenUtil.getTokenUserId()));
                entity.setPath(newName);
                entity.setRealPath(newName);
                entity.setRealName(filename);
                entity.setName(filename);
                entity.setUploadTime(new Date());
                entity.setFileType(1);
                entity.setDownloadCount(0);
                //在集合中添加
                list.add(entity);
            } catch (IOException e) {
                e.printStackTrace();
                return ResponseCode.buildFailed(Message.UPLOAD_FAILURE);
            }
        }
        fileService.saveBatch(list);
        return ResponseCode.buildSuccess(Message.UPLOAD_SUCCESS);
    }

    /**
     * @param goodId 商品id
     * @return java.lang.Object
     * @description 用户下载文件，需是已经付费的商品
     * @author mgl
     * @date 2023/7/16 11:00
     */
    @UserLoginToken
    @GetMapping("/downloadFile")
    public Object downloadFile(@RequestParam("goodId") Integer goodId, HttpServletResponse response) throws IOException {
        String userId = TokenUtil.getTokenUserId();
        //String userId = "2";
        String filePath = fileService.getFilePath(Integer.valueOf(userId), goodId);
        java.io.File file = new java.io.File(filePath);
        if (!file.exists()) {
            return ResponseCode.buildFailed(Message.FILE_DOWNLOAD_NOT_PERMITTED);
        }

        String fileName = file.getName();
        // 重置response
        response.reset();
        // ContentType，即告诉客户端所发送的数据属于什么类型
        response.setContentType("application/octet-stream; charset=UTF-8");
        // 获得文件的长度
        response.setHeader("Content-Length", String.valueOf(file.length()));
        // 设置编码格式
        response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8"));
        // 发送给客户端的数据
        OutputStream outputStream = response.getOutputStream();
        byte[] buff = new byte[1024];
        BufferedInputStream bis = null;
        // 读取文件
        bis = new BufferedInputStream(new FileInputStream(new java.io.File(filePath)));
        int i = bis.read(buff);
        // 只要能读到，则一直读取
        while (i != -1) {
            // 将文件写出
            outputStream.write(buff, 0, buff.length);
            // 刷出
            outputStream.flush();
            i = bis.read(buff);
        }
        return ResponseCode.buildSuccess(Message.FILE_DOWNLOAD_SUCCESS);
    }

    /**
     * @description 文件下载接口，妥协版
     * @param goodId 商品id
     * @param userId 用户id
     * @param response http响应
     * @return java.lang.Object
     * @author mgl
     * @date 2023/8/12 11:44
     */
    @GetMapping("/downloadFile2")
    public Object downloadFile(Integer goodId,Integer userId,HttpServletResponse response) throws IOException {
        //String userId = "2";
        String filePath = fileService.getFilePath(Integer.valueOf(userId), goodId);
        java.io.File file = new java.io.File(filePath);
        if (!file.exists()) {
            return ResponseCode.buildFailed(Message.FILE_DOWNLOAD_NOT_PERMITTED);
        }

        String fileName = file.getName();
        // 重置response
        response.reset();
        // ContentType，即告诉客户端所发送的数据属于什么类型
        response.setContentType("application/octet-stream; charset=UTF-8");
        // 获得文件的长度
        response.setHeader("Content-Length", String.valueOf(file.length()));
        // 设置编码格式
        response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8"));
        // 发送给客户端的数据
        OutputStream outputStream = response.getOutputStream();
        byte[] buff = new byte[1024];
        BufferedInputStream bis = null;
        // 读取文件
        bis = new BufferedInputStream(new FileInputStream(new java.io.File(filePath)));
        int i = bis.read(buff);
        // 只要能读到，则一直读取
        while (i != -1) {
            // 将文件写出
            outputStream.write(buff, 0, buff.length);
            // 刷出
            outputStream.flush();
            i = bis.read(buff);
        }
        return ResponseCode.buildSuccess(Message.FILE_DOWNLOAD_SUCCESS);
    }
}

